import { reponseConfig, requestConfig, API_CONFIG } from "./config/index";

import { requestLogger } from "./log/index";

export function UPLOAD({ url, param, data, filePath, name = "file", formData = {}, ...config }) {
    return new Promise((resolve, reject) => {
        let _url = API_CONFIG.UPLOAD_HOST + url;
        if (param) {
            const arrKey = Object.keys(param);
            arrKey.forEach((key, index) => {
                if (index === 0) {
                    _url += `?${key}=${param[key]}`;
                    return;
                }
                _url += `&${key}=${param[key]}`;
            })
        }
        uni.uploadFile({
            ...config,
            url: _url,
            filePath,
            name,
            formData,
            success(res) {
                if (res.statusCode === 200) {
                    resolve(reponseConfig.response(res));
                }
            },
            complete(response) {
                const { header } = config;
                requestLogger({ url, method: "UPLOAD", header, data, response });
                if (response.statusCode !== 200) {
                    reject(reponseConfig.error(response));
                }
            }

        });
    });
}